package csc.fresher.finalgroupfour.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import csc.fresher.finalgroupfour.domain.User;

@Repository("userDAO")
public class UserDAO {
	@PersistenceContext
	private EntityManager em; // Entity Manager is acquired by container.
	
	/**
	 * Add a new user.
	 * @param user
	 */
	@Transactional
	public void addUser(User user) {
		em.persist(user);
	}
	
	/**
	 * List all users in DB.
	 * @return
	 */
	@Transactional
	public List<User> listUsers() {
		List<User> users = new ArrayList<User>();
		TypedQuery<User> query = em.createQuery("SELECT a FROM User a", User.class);
		
		users = query.getResultList();
		if (users.size() > 0) {
			return users;
		}
		return null;
	}
	
	@Transactional
	public List<User> listNormalUsers() {
		List<User> users = new ArrayList<User>();
		TypedQuery<User> query = em.createQuery("SELECT a FROM User a, Role r WHERE a.role = r AND r.role = :role", 
				User.class);
		query.setParameter("role", "ROLE_USER");
		
		users = query.getResultList();
		if (users.size() > 0) {
			return users;
		}
		return null;
	}
	
	/**
	 * Update a user's information
	 * @param user
	 */
	@Transactional
	public void updateUser(User user) {
		em.merge(user);
	}
	
	/**
	 * Remove a user from database.
	 * @param user
	 */
	@Transactional
	public void deleteUser(User user) {
		em.remove(user);
	}
	
	/**
	 * Find weather a user existed or not.
	 * @param user
	 * @return
	 */
	@Transactional
	public User findUser(String loginId) {
		List<User> users=null;
		try {
			TypedQuery<User> query = em.createQuery("SELECT u FROM User u where u.loginId = :id", User.class);
			query.setParameter("id", loginId);
			users = query.getResultList();
			if (users.size() > 0) {
				return users.get(0);
			}
		}
		catch (Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
}

